package cn.juque.jdfsystem.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.juque.common.constants.MessageEnum;
import cn.juque.common.constants.YesOrNoEnum;
import cn.juque.common.exception.AppException;
import cn.juque.jdfsystem.cache.ConfigInfoCache;
import cn.juque.jdfsystem.entity.ConfigInfo;
import cn.juque.jdfsystem.mapper.ConfigInfoMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>ConfigInfoHelper</li>
 * </ul>
 * @date 2023-01-09 16:31:50
 **/
@Component("configInfoHelper")
public class ConfigInfoHelper {

    public static final String BEAN = "configInfoHelper";

    @Resource
    private ConfigInfoMapper configInfoMapper;

    @Resource
    private ConfigInfoCache configInfoCache;

    public String getConfigValue(String code) {
        if (CharSequenceUtil.isEmpty(code)) {
            throw new AppException(MessageEnum.PARAM_NULL.getCode(), "配置编码不能为空");
        }
        Map<String, ConfigInfo> map = this.configInfoCache.getAllConfig();
        ConfigInfo configInfo = map.get(code);
        if (null == configInfo) {
            ConfigInfo query = new ConfigInfo();
            query.setConfigCode(code);
            List<ConfigInfo> list = this.configInfoMapper.selectList(new QueryWrapper<>(query));
            if (CollUtil.isEmpty(list)) {
                throw new AppException(MessageEnum.PARAM_NULL.getCode(), "【" + code + "】配置编码不存在");
            }
            configInfo = list.get(0);
            this.configInfoCache.update(configInfo);
        }
        if (YesOrNoEnum.NO.getCode().equals(configInfo.getValidFlag())) {
            throw new AppException(MessageEnum.PARAM_ERROR.getCode(), "【" + code + "】配置编码未启用");
        }
        return configInfo.getConfigValue();
    }
}
